package com.aliyun.commons.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;

import com.aliyun.commons.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

/**
 * Redis 服务实现
 *
 * 
 * @date 2024/11/26
 */
@Slf4j
@Service
public class CacheServiceImpl implements CacheService {

    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String, Object> objectRedisTemplate;
    @Resource(name = "counterRedisTemplate")
    private RedisTemplate<String, Integer> counterRedisTemplate;
    @Resource(name = "scriptRedisTemplate")
    private RedisTemplate<String, Integer> scriptRedisTemplate;

    @Override
    public void setValue(String key, Object value, long expireSeconds) {
        if (expireSeconds <= 0) {
            objectRedisTemplate.opsForValue().set(key, value);
            return;
        }
        objectRedisTemplate.opsForValue().set(key, value, expireSeconds, TimeUnit.SECONDS);
    }

    @Override
    public <T> T getValue(String key, Class<T> clazz) {
        JSONObject value = (JSONObject)objectRedisTemplate.opsForValue().get(key);
        if (value == null) {
            return null;
        }
        return value.toJavaObject(clazz);
    }

    @Override
    public void deleteKey(String key) {
        objectRedisTemplate.delete(key);
    }

    @Override
    public Integer getCounter(String key) {
        return counterRedisTemplate.opsForValue().get(key);
    }

    @Override
    public void initCounter(String key, int initialValue, long expireSeconds) {
        if (expireSeconds <= 0) {
            counterRedisTemplate.opsForValue().set(key, initialValue);
            return;
        }
        counterRedisTemplate.opsForValue().set(key, initialValue, expireSeconds, TimeUnit.SECONDS);
    }

    @Override
    public void incrementCounter(String key, int increment) {
        counterRedisTemplate.opsForValue().increment(key, increment);
    }

    @Override
    public Long executeLuaScript(String script, List<String> keys, Object... args) {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        return scriptRedisTemplate.execute(redisScript, keys, args);
    }
}
